<?php

namespace app\admin\controller;

use think\exception\ValidateException;
use app\model\Category;

class CategoryController extends Base
{

	function index()
	{
		$keyword = input('post.keyword', '', 'serach_in');
		$ptype = input('post.ptype', '', 'serach_in');

		$query = Category::field('id,title,ptype,deliverymode,status,create_time,image,sort,pid')->where('weid', weid());

		if (!empty($ptype)) {
			$query->where('ptype', $ptype);
		}
		if (!empty($keyword)) {
			$query->where('title', 'like', '%' . $keyword . '%');
		}

		$list = $query->order('sort asc')->select()->toArray();

		foreach ($list as &$vo) {
			$vo['image'] = toimg($vo['image']);
			$vo['create_time'] = time_format($vo['create_time']);
			$vo['ptype'] = getptype($vo['ptype']);
			$vo['deliverymode'] = getdeliverymode($vo['deliverymode']);
		}
		$data['data'] = _generateListTree($list, 0, ['id', 'pid']);

		return $this->json($data);
	}

	function listUpdate()
	{
		$data = only('id,status,sort');
		if (!$data['id']) throw new ValidateException('参数错误');
		Category::update($data);

		return $this->json(['msg' => '操作成功']);
	}

	public function update()
	{
		$id = $this->request->post('id');
		$data = input('post.');

		$data['pid'] = (int)$data['pid'];

		if (empty($id)) {
			$data['weid'] = weid();
			$data['create_time'] = time();
			try {
				$res = Category::create($data);
				if ($res->id && empty($data['sort'])) {
					Category::update(['sort' => $res->id, 'id' => $res->id]);
				}
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '添加成功', 'data' => $res->id]);
		} else {
			try {
				Category::update($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '修改成功']);
		}
	}

	function getInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		if (!$id) throw new ValidateException('参数错误');
		$res = Category::find($id);
		if ($res) {
			$res = $res->toArray();
			$res['image'] = toimg($res['image']);
		}

		return $this->json(['data' => $res]);
	}

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
		Category::destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}

	function getField()
	{
	    $ptype = input('post.ptype');
		$data['pids'] = _generateSelectTree(Category::getpcarray($ptype));
		$data['ptypearray'] = getptype();
		$data['deliverymodearray'] = getdeliverymode();

		return $this->json(['data' => $data]);
	}
	function getTree()
	{

		$alldata[0]['val'] = '0';
		$alldata[0]['key'] = '全部分类';
		$alldata[0]['pid'] = 0;
		
		$cdata = _generateSelectTree(Category::getpcarray());

		$data = array_merge($alldata,$cdata);
		return $this->json(['data' => $data]);
	}
}
